//microcommand define textoverlay
function isShorthandFontProp(cssValue) {
  return /^\s*(?:(?:normal|italic|oblique(?:\s+(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?(?:deg|grad|rad|turn))?|small-caps|(?:ultra-|extra-|semi-)?(?:condensed|expanded)|bold|lighter|bolder|(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?)\s+)*(?:(?:[x]{1,2}-)?(?:large|small)|medium|smaller|larger|(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?(?:px|cm|mm|Q|in|pc|pt|%|vh|vw|vi|vb|vmin|max|cap|ch|em|ex|ic|lh|rem|rlh))(?=[\/\s])/.test(cssValue)
}
inject(["lnnbotSideloadFonts", "puppeteer", "canvas"])
signature("<text> <image:image>", { checkArgCount: true, checkUnknown: true })
option("html", "-H, -E", { descPath: "commands.imagify.options.html" })
option("font", "-f <css-font>", { descPath: "commands.imagify.options.font" })
option("fontSize", "-s <css-font-size>", { descPath: "commands.imagify.options.fontSize" })
option("lang", "-l <code>", { descPath: "commands.imagify.options.lang" })
option("color", "-c <css-color>")
option("strokeWidth", "-S <number>", { fallback: 1 })
option("strokeColor", "-C <css-color>")
option("writingMode", "<css-writing-mode>", { hidden: true })
option("writingMode", "-R, --vertical-rl", { value: "vertical-rl" })
option("writingMode", "-L, --vertical-lr", { value: "vertical-lr" })
option("align", "-a <start|end|center|justify>", { fallback: "center" })
option("blockAlign", "-b <start|end|center>")
option("padding", "-p <css-length>", { fallback: "0.25rem" })
option("padding", "-P, --no-padding", { value: "0" })
action(async ({ session, options }, text, img) => {
  const image = await ctx.canvas.loadImage(img.src)
  const { naturalWidth, naturalHeight } = image
  image.dispose()
  let width = naturalWidth
  let height = naturalHeight
  // 将长边调整为 160px
  if (width > height) {
    height = height / width * 160
    width = 160
  } else {
    width = width / height * 160
    height = 160
  }
  const font = options.font || "Noto Sans CJK SC, Plangothic P1, Plangothic P2"
  const divStyles = {
    "white-space": "pre-wrap",
    "overflow-wrap": "break-word",
    "writing-mode": options.writingMode,
    "text-align": options.align,
    "inline-size": "100%",
    "position": "absolute",
    "color": options.color,
    "-webkit-text-stroke-width": `${options.strokeWidth || 0}px`,
    "-webkit-text-stroke-color": options.strokeColor || "hsl(from currentColor 0 0 calc(calc(50 - l) * 114514))",
    "paint-order": "stroke fill",
    [isShorthandFontProp(font) ? "font" : "font-family"]: font,
    "font-size": options.fontSize,
  }
  if (options.blockAlign === "center")
    Object.assign(divStyles, {
      "inset-block": "0",
      "display": "flex",
      "justify-content": "center",
    })
  else divStyles[`inset-block-${options.blockAlign || "end"}`] = options.padding
  const svg = /*xml*/`
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${naturalWidth}" height="${naturalHeight}">
      <style>${h.escape(await ctx.lnnbotSideloadFonts.getDeclarations())}</style>
      <image width="${width}" height="${height}" href="${img.src}"/>
      <foreignObject x="0" y="0" width="${width}" height="${height}">
        <div xmlns="http://www.w3.org/1999/xhtml"
          lang="${h.escape(options.lang || "zh-CN")}"
          style="${Object.entries(divStyles).filter(([, v]) => v).map(([k, v]) => `${k}:${v}`).join(";")}"
        >${options.html ? text : h.escape(text)}</div>
      </foreignObject>
    </svg>`.trim()
  ctx.logger.debug(svg)
  return await ctx.puppeteer.render(svg, async page => {
    await page.setViewport({ width: 1080, height: 1080, deviceScaleFactor: 1 })
    const el = await page.$("svg")
    return h.image(await page.screenshot({ clip: await el.boundingBox(), omitBackground: true }), "image/png")
  })
})
locale("zh-CN", {
  description: "在图片上添加文字覆盖",
  arguments: {
    text: "文字内容",
    image: "图片",
  },
  options: {
    color: "文字颜色",
    strokeWidth: "文字描边宽度",
    strokeColor: "文字描边颜色",
    strokeOutset: "文字描边外扩",
    writingMode: "文字书写方向",
    "writingMode.vertical-rl": "文字书写方向：右起竖排",
    "writingMode.vertical-lr": "文字书写方向：左起竖排",
    align: "文字对齐方式",
    blockAlign: "文字垂直对齐方式",
    padding: "边距",
    "padding.0": "无边距",
  },
})